﻿using Domain.Model;
using Infrastructure.Error;
using Microsoft.Extensions.Logging;
using OtherLib.TenXun;
using System;
using System.Collections.Generic;
using System.Text;
using Tlh.Common;
using Utility;

namespace Domain.Services
{
    public class IMService
    {
        public ILogger<IMService> Logger { get; set; }

        public string GetIMUser(UserInfoAggregate u)
        {
            return $"a{u.Phone}";
        }
        public string GetIMUserPhone(string iMUser)
        {
            return iMUser.Substring(1);
        }
        public bool CreateIMUser(UserInfoAggregate u)
        {
            var authorization = "XSjq9C70bRcyFjmn";
            var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
                $"<user><username>{GetIMUser(u)}</username><password>{GetIMUserPwd(u)}</password><name>{u.NickName}</name>" +
                $"<properties><property key=\"ID\" value=\"{u.ID}\"/></properties></user>";

            var ret = HttpUtil.PostXml("http://im.jhgoulaifu.com:9090/plugins/restapi/v1/users", xml, authorization).GetAwaiter().GetResult();
            if (string.IsNullOrWhiteSpace(ret)) return true;

            throw new BizException(ret);
        }

        public bool UpdateIMUser(UserInfoAggregate u)
        {
            var authorization = "XSjq9C70bRcyFjmn";
            var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
                $"<user><username>{GetIMUser(u)}</username><password>{GetIMUserPwd(u)}</password><name>{u.NickName}</name>" +
                $"<properties><property key=\"ID\" value=\"{u.ID}\"/></properties></user>";

            var ret = HttpUtil.PutXml("http://im.jhgoulaifu.com:9090/plugins/restapi/v1/users/a" + u.Phone, xml, authorization).GetAwaiter().GetResult();
            if (string.IsNullOrWhiteSpace(ret)) return true;

            Logger.LogException(new BizException(ret));
            return false;
        }

        public string GetIMUserPwd(UserInfoAggregate u)
        {
            return Md5Util.GetMD5Hash(u.ID + u.Phone);
        }


        public string GetTXUserSig(UserInfoAggregate u)
        {
            TLSSigAPIv2 tLSSigAPIv2 = TLSSigAPIv2.GetInstance();

            var sign = tLSSigAPIv2.genUserSig(GetIMUser(u));

            return sign;
        }

    }
}
